package com.smartcommunity.job;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.smartcommunity.api.user.UserApi;
import com.smartcommunity.cache.Cache;
import com.smartcommunity.dao.fullSearch.FullCountStatisticsDao;
import com.smartcommunity.entity.fullSearch.FullCountStatistics;
import com.smartcommunity.es.common.EsBasedataEnum;
import com.smartcommunity.es.common.EsIndex;
import com.smartcommunity.es.common.EsRestUtils;
import com.smartcommunity.utils.DateUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 全息档案统计任务
 */
@Component
@Slf4j
public class FullSeachCountJob {

	@Autowired
    private EsRestUtils eSRestUtils;
	@Autowired
    private UserApi userApi;
	@Autowired
    private FullCountStatisticsDao fullCountStatisticsDao;
	
	@Scheduled(cron = "0 0 0 * * ? ")
	public void fullSearchCount() {
		log.info("全息档案统计任务开始");
		try {
			//获取所有用户对应的角色
			List<Map<String, Object>> userRoleIds = (List<Map<String, Object>>) userApi.getAllUserRoleId().getData();
			Map<String, List<String>> userRoleMap = new HashMap<>();
			for(Map<String, Object> tmp:userRoleIds) {
				String userId = tmp.get("userId").toString();
				String roleId = tmp.get("roleId").toString();
				List<String> roleIds;
				if(!userRoleMap.containsKey(userId)) {
					roleIds = new ArrayList<>();
				}else {
					roleIds = userRoleMap.get(userId);
				}
				roleIds.add(roleId);
				userRoleMap.put(userId, roleIds);
			}
			//根据用户角色获取小区
			for(String userId:userRoleMap.keySet()) {
				List<String> roleIds = userRoleMap.get(userId);
				Set<String> villageCodes = new HashSet<>();
		        for (String roleId: roleIds) {
		            String villageCode = Cache.REL_ROLE_VILLAGE.get(roleId);
		            if(StringUtils.isEmpty(villageCode)){
		                continue;
		            }
		            villageCodes.addAll(Arrays.asList(villageCode.replaceAll("'", "").split(",")));
		        }
				Long peopleCount = countTotal(EsBasedataEnum.PEOPLE.getIntValue(), villageCodes);
				Long vehicleCount = countTotal(EsBasedataEnum.VEHICLE.getIntValue(), villageCodes);
				Long houseCount = countTotal(EsBasedataEnum.HOUSE.getIntValue(), villageCodes);
				Long vidCount = countTotal(EsBasedataEnum.VID.getIntValue(), villageCodes);
				FullCountStatistics fullCountStatistics = new FullCountStatistics();
				fullCountStatistics.setUserId(Integer.parseInt(userId));
				fullCountStatistics.setPeopleCount(peopleCount);
				fullCountStatistics.setVehicleCount(vehicleCount);
				fullCountStatistics.setHouseCount(houseCount);
				fullCountStatistics.setVidCount(vidCount);
				fullCountStatisticsDao.saveFullCountStatistics(fullCountStatistics);
			}
			log.info("全息档案统计任务结束");
		}catch (Exception e) {
			log.error("全息档案统计任务失败", e);
		}
	}
	
	private Long countTotal(int dataType, Set<String> villageCodes) throws Exception {
		String[] index = new String[]{EsIndex.BASEDATA};
		BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
		queryBuilder.must(QueryBuilders.termsQuery("villageCode", villageCodes));
		queryBuilder.must(QueryBuilders.matchPhraseQuery("dataType", dataType));
		queryBuilder.must(QueryBuilders.rangeQuery("mrowTime").to(DateUtils.getDayStart(new Date())));
		return eSRestUtils.getTotalRecords(index, queryBuilder);
	}
}
